// 二分查找算法-C语言实现
#include <stdio.h>

int binary_search_num[15] = {
    1, 2, 3, 4, 5,
    6, 7, 8, 9, 10,
    11, 12, 13, 14, 15
};

int binary_search(int *arr, int size, int key)
{
    int start = 0;
    int end = size - 1;
    int mid = 0;
    // 边界条件
    if (key <= arr[start])
    {
        return start;
    }
    if (key >= arr[end])
    {
        return end;
    }
    // 二分查找
    while (start <= end)
    {
        mid = start + (end - start) / 2;
        if (arr[mid] == key)
        {
            return mid;
        }
        else if (arr[mid] < key)
        {
            if (mid + 1 < size && arr[mid + 1] == key)
            {
                return mid + 1;
            }
            start = mid + 1;
        }
        else if (arr[mid] > key)
        {
            if (mid - 1 >= 0 && arr[mid + 1] == key)
            {
                return mid + 1;
            }
            end = mid - 1;
        }
        //近似值靠近
        if (start == end || start + 1 == end)
        {
            return start;
        }
    }
    return -1;
}


int main()
{
    int key = 14;
    int key_index = binary_search(binary_search_num, sizeof(binary_search_num) / sizeof(int), key);

    printf("key:%d, index:%d\r\n", key, key_index);

    return 0;
}